<?php
/**
 * 商品 业务层
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-05
 * Time: 17:58
 */

namespace App\Services\Manager;


use App\Models\Brand;
use App\Models\Good;
use App\Models\Goods;
use App\Models\GoodStock;
use App\Models\GoodStockBatch;
use App\Models\GoodStockBatchLog;
use App\Models\InventoryLog;
use App\Models\Kind;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\PartitionTask;
use App\Models\Team;
use App\Models\TeamTask;
use App\Models\TeamTaskUser;
use App\Models\User;
use App\Models\UserManager;
use App\Models\UserRelation;
use App\Models\UserSaleLog;

class OrderService
{

    public function setSale($orderNo, $userId, $order, $user, $payType)
    {
        $time = date("Y-m-d H:i:s");
        //$month = date("Y-m",strtotime("-1 Month"));
        $month = date("Y-m");
        $isCount = 0;
        $deductPrice = 0;
        $partitionTaskId = null;
        $upOrder = [];
        $upOrder['partitionId'] = null;
        $upOrder['teamId'] = null;
        $upOrder['partitionTaskId'] = null;
        $upOrder['teamTaskId'] = null;
        $profitPrice = 0;
        $orderDetail = OrderDetail::where('orderId', $order['orderId'])->get()->toArray();
        foreach ($orderDetail as $value) {
            GoodStock::where('goodStockId', $value['goodStockId'])->increment('supply', -$value['goodNum']);
            GoodStock::where('goodStockId', $value['goodStockId'])->increment('purchaseNum', $value['goodNum']);
            Good::where('goodId', $value['goodId'])->increment('purchaseNum', $value['goodNum']);
            if ($value['level'] == 1) {
                $rate = $value['oneLevelRatio'];
            } else if ($value['level'] == 2) {
                $rate = $value['twoLevelRatio'];
            } else if ($value['level'] == 3) {
                $rate = $value['threeLevelRatio'];
            } else {
                $rate = 0;
            }
            $totalDetailPrice = $value['price'] * $value['goodNum'];
//            $totalCostPrice = $value['costPrice'] * $value['goodNum'];
//            $profitPrice = $totalDetailPrice - $totalCostPrice;
//            if ($profitPrice < 0) {
//                $deductPrice = 0;
//            } else {
//                $deductPrice = $deductPrice + (intval(($profitPrice) / 100) * $rate);
//            }
            $deductPrice = $deductPrice + (intval(($totalDetailPrice) / 100) * $rate);
        }
        if (isset($user['inviteUserId'])) {
            //查询是否有上级,如果有则展开
            $inviteUser = User::where(['userId' => $user['inviteUserId']])->first();
            if (isset($inviteUser) && $inviteUser['level'] == 1) {
                //查询其本月是否申请了绩效
                $teamTask = Team::select('t2.teamTaskId', 't2.teamId', 't1.partitionId', 't2.taskType')
                    ->from((new Team())->getTable() . ' as t1')
                    ->join((new TeamTask())->getTable() . ' as t2', function ($query) use ($month) {
                        $query->on('t1.teamId', '=', 't2.teamId')
                            ->where('t2.createTime', 'like', "%$month%");
                    })
                    ->where('t1.userId', $user['inviteUserId'])
                    ->first();
                if ($teamTask) {
                    //判断绩效类型 整站 我的
                    $good = Good::where('goodId', $order['goodId'])->first();
                    if ($teamTask['taskType'] == "ALL") {
                        $isCount = 1;
                    } else {
                        if ($teamTask['membershipId'] == $good['membershipId']) {
                            $isCount = 1;
                        }
                    }
                    if ($isCount) {
                        //接了绩效。开始计算
                        //查询本月是否为其添加了记录
                        if (isset($teamTask['partitionId'])) {
                            $partitionTask = PartitionTask::where('partitionId', $teamTask['partitionId'])->where('isNew', 1)->first();
                            if ($partitionTask) {
                                $partitionTaskId = $partitionTask['partitionTaskId'];
                            }
                        }
                        $upOrder['partitionId'] = $teamTask['partitionId'];
                        $upOrder['teamId'] = $teamTask['teamId'];
                        $upOrder['partitionTaskId'] = $partitionTaskId;
                        $upOrder['teamTaskId'] = $teamTask['teamTaskId'];
                        if (isset($partitionTaskId)) {
                            if ($order['level'] == 1) {
                                PartitionTask::where('partitionTaskId', $partitionTaskId)->update([
                                    'fulfillOneLevelUserOrderNum' => \DB::raw('fulfillOneLevelUserOrderNum + 1'),
                                    'fulfillOneLevelUserOrderPriceNum' => \DB::raw('fulfillOneLevelUserOrderPriceNum + ' . $order['paymentPrice'])
                                ]);
                            } else if ($order['level'] == 2) {
                                PartitionTask::where('partitionTaskId', $partitionTaskId)->update([
                                    'fulfillTwoLevelUserOrderNum' => \DB::raw('fulfillTwoLevelUserOrderNum + 1'),
                                    'fulfillTwoLevelUserOrderPriceNum' => \DB::raw('fulfillTwoLevelUserOrderPriceNum + ' . $order['paymentPrice'])
                                ]);
                            } else if ($order['level'] == 3) {
                                PartitionTask::where('partitionTaskId', $partitionTaskId)->update([
                                    'fulfillThereLevelUserOrderNum' => \DB::raw('fulfillThereLevelUserOrderNum + 1'),
                                    'fulfillThereLevelUserOrderPriceNum' => \DB::raw('fulfillThereLevelUserOrderPriceNum + ' . $order['paymentPrice'])
                                ]);
                            }
                        }
                        if (isset($teamTask['teamTaskId'])) {
                            TeamTask::where('teamTaskId', $teamTask['teamTaskId'])->update([
                                'finishOrderNum' => \DB::raw('finishOrderNum + 1'),
                                'finishOrderPriceNum' => \DB::raw('finishOrderPriceNum + ' . $order['paymentPrice'])
                            ]);
                        }
                        $teamTaskUser = TeamTaskUser::where('userId', $order['userId'])->where('createTime', 'like', "%$month%")->lockForUpdate()->first();
                        if ($teamTaskUser) {
                            //如果有则修改
                            $upTeamTaskUser = [];
                            $upTeamTaskUser['orderNum'] = $teamTaskUser['orderNum'] + 1;
                            $upTeamTaskUser['orderPriceNum'] = $teamTaskUser['orderPriceNum'] + $order['paymentPrice'];
                            $upTeamTaskUser['alreadyDistributionPrice'] = $teamTaskUser['alreadyDistributionPrice'] + $deductPrice;
                            $upTeamTaskUser['distributionPrice'] = $teamTaskUser['distributionPrice'] + $deductPrice;
                            TeamTaskUser::where('teamTaskUserId', $teamTaskUser['teamTaskUserId'])->update($upTeamTaskUser);
                        } else {
                            //如果没则添加
                            $teamTaskUser = [];
                            $teamTaskUser['userId'] = $userId;
                            $teamTaskUser['membershipId'] = $user['membershipId'];
                            $teamTaskUser['orderNum'] = 1;
                            $teamTaskUser['orderPriceNum'] = $order['paymentPrice'];
                            $teamTaskUser['alreadyDistributionPrice'] = $deductPrice;
                            $teamTaskUser['distributionPrice'] = $deductPrice;
                            $teamTaskUser['teamTaskId'] = $teamTask['teamTaskId'];
                            $teamTaskUser['teamId'] = $teamTask['teamId'];
                            $teamTaskUser['inviteUserId'] = $user['inviteUserId'];
                            $teamTaskUser['createTime'] = $time;
                            $teamTaskUser['taskType'] = $teamTask['taskType'];
                            $teamTaskUser['partitionId'] = $teamTask['partitionId'];
                            $teamTaskUser['partitionTaskId'] = $partitionTaskId;
                            TeamTaskUser::insert($teamTaskUser);
                        }
                        User::where('userId', $userId)->update([
                            'totalOrderNum' => \DB::raw('totalOrderNum + 1'),
                            'totalOrderPriceNum' => \DB::raw('totalOrderPriceNum + ' . $order['paymentPrice']),
                            'totalAlreadyDistributionPrice' => \DB::raw('totalAlreadyDistributionPrice + ' . $deductPrice),
                            'totalDistributionPrice' => \DB::raw('totalDistributionPrice + ' . $deductPrice)
                        ]);
                    }
                }
                //开始计算分销
                $userRelation = UserRelation::where('userId', $userId)->first();
                $userSaleList = [];
                if ($userRelation) {
                    $relationList = explode(';', $userRelation['relationList']);
                    unset($value);
                    foreach ($relationList as $value) {
                        $userSale = User::select('t1.userId', 't2.teamTaskId', 't1.level')
                            ->from((new User())->getTable() . ' as t1')
                            ->join((new TeamTask())->getTable() . ' as t2', function ($query) use ($month) {
                                $query->on('t1.userId', '=', 't2.userId')
                                    ->where('t2.createTime', 'like', "%$month%");
                            })
                            ->where('t1.userId', $value)
                            ->first();
                        if (isset($userSale)) {
                            if ($userSale['level'] == 1) {
                                $userSaleList[] = $userSale->toArray();
                            } else {
                                break;
                            }
                        }
                    }
                }
                $userSaleList = array_values($userSaleList);
                if (isset($userSaleList[0])) {
                    unset($value);
                    $userSaleLogList = [];
                    $userPerformanceList = [];
                    foreach ($orderDetail as $value) {
                        if ($value['level'] == 1) {
                            $zRate = $value['oneLevelRatio'];
                        } else if ($value['level'] == 2) {
                            $zRate = $value['twoLevelRatio'];
                        } else if ($value['level'] == 3) {
                            $zRate = $value['threeLevelRatio'];
                        } else {
                            $zRate = 0;
                        }
                        $totalDetailPrice = $value['price'] * $value['goodNum'];
                        $deductPrice = (intval(($totalDetailPrice) / 100) * $zRate);
                        unset($key);
                        unset($val);
                        foreach ($userSaleList as $key => $val) {
                            $isInvite = 0;
                            if ($val['userId'] != $inviteUser['userId']) {
                                $rate = 1/pow(2, $key);
                                $salePrice = intval($deductPrice * $rate);
                            } else {
                                $rate = $zRate/100;
                                $isInvite = 1;
                                $salePrice = $deductPrice;
                            }
                            $salePrice = intval($salePrice);
                            if ($salePrice < 1) {
                                break;
                            }
                            if (isset($userPerformanceList[$val['userId']])) {
                                $userPerformanceList[$val['userId']] = $userPerformanceList[$val['userId']] + $salePrice;
                            } else {
                                $userPerformanceList[$val['userId']]['teamTaskId'] = $val['teamTaskId'];
                                $userPerformanceList[$val['userId']]['salePrice'] = $salePrice;
                                $userPerformanceList[$val['userId']]['isInvite'] = $isInvite;
                            }
                            $userSaleLog = [];
                            $userSaleLog['userId'] = $val['userId'];
                            $userSaleLog['orderId'] = $value['orderId'];
                            $userSaleLog['orderDetailId'] = $value['orderDetailId'];
                            $userSaleLog['salePrice'] = $salePrice;
                            $userSaleLog['isInvite'] = $isInvite;
                            $userSaleLog['level'] = $value['level'];
                            $userSaleLog['price'] = $value['price'];
                            $userSaleLog['num'] = $value['goodNum'];
                            $userSaleLog['rate'] = $rate;
                            $userSaleLog['sort'] = $key;
                            $userSaleLog['createTime'] = $time;
                            $userSaleLog['isAdd'] = 1;
                            $userSaleLog['teamTaskId'] = $val['teamTaskId'];
                            $userSaleLogList[] = $userSaleLog;
                        }
                    }
                    UserSaleLog::insert($userSaleLogList);
                    unset($value);
                    foreach ($userPerformanceList as $value) {
                        if ($value['isInvite']) {
                            TeamTask::where('teamTaskId', $value['teamTaskId'])->update([
                                'monthPerformance' => \DB::raw('monthPerformance + ' . $value['salePrice'])
                            ]);
                        } else {
                            TeamTask::where('teamTaskId', $value['teamTaskId'])->update([
                                'addPerformance' => \DB::raw('addPerformance + ' . $value['salePrice'])
                            ]);
                        }
                    }
                }
            }
        }
        User::where('userId', $userId)->update([
            'orderFrequency' => \DB::raw('orderFrequency + 1')
        ]);
        //然后为其订单变换状态
        Order::where('orderId', $order['orderId'])->update([
            'payTime' => $time,
            'payType' => $payType,
            'isCount' => $isCount,
            'orderStatus' => "PAYMENT",
            'orderFrequency' => $user['orderFrequency'] + 1,
            'retreatFrequency' => $user['retreatFrequency'],
            'partitionId' => $upOrder['partitionId'],
            'teamId' => $upOrder['teamId'],
            'partitionTaskId' => $upOrder['partitionTaskId'],
            'teamTaskId' => $upOrder['teamTaskId'],
        ]);
    }
}